{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 偶数号 2号作业 20241126"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2.输出9x9乘法口诀表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1*1=1\t\n",
      "1*2=2\t2*2=4\t\n",
      "1*3=3\t2*3=6\t3*3=9\t\n",
      "1*4=4\t2*4=8\t3*4=12\t4*4=16\t\n",
      "1*5=5\t2*5=10\t3*5=15\t4*5=20\t5*5=25\t\n",
      "1*6=6\t2*6=12\t3*6=18\t4*6=24\t5*6=30\t6*6=36\t\n",
      "1*7=7\t2*7=14\t3*7=21\t4*7=28\t5*7=35\t6*7=42\t7*7=49\t\n",
      "1*8=8\t2*8=16\t3*8=24\t4*8=32\t5*8=40\t6*8=48\t7*8=56\t8*8=64\t\n",
      "1*9=9\t2*9=18\t3*9=27\t4*9=36\t5*9=45\t6*9=54\t7*9=63\t8*9=72\t9*9=81\t\n"
     ]
    }
   ],
   "source": [
    "def print_multiplication_table():\n",
    "    for i in range(1, 10):#i从1到9\n",
    "        for j in range(1, i + 1):#j从1到i\n",
    "            print(f\"{j}*{i}={i * j}\", end=\"\\t\")#当等号前后相等换行\n",
    "        print()\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    print_multiplication_table()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4.输入一个任意正整数，输出分解质因数。例如：输入90,打印出90=2*3*3*5。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "90=2*3*3*5\n"
     ]
    }
   ],
   "source": [
    "def prime_factors(n):\n",
    "    factors = []\n",
    "    while n % 2 == 0:# 处理2的因数\n",
    "        factors.append(2)\n",
    "        n = n // 2\n",
    "\n",
    "    factor = 3\n",
    "    while factor * factor <= n:\n",
    "        while n % factor == 0:\n",
    "            factors.append(factor)\n",
    "            n = n // factor\n",
    "        factor += 2# 处理奇数因数\n",
    "\n",
    "    # 如果n本身就是一个大于2的质数\n",
    "    if n > 2:\n",
    "        factors.append(n)\n",
    "\n",
    "    return factors\n",
    "\n",
    "def main():\n",
    "    try:\n",
    "        num = int(input(\"请输入一个正整数: \"))\n",
    "        if num <= 0:\n",
    "            raise ValueError(\"请输入一个大于0的正整数。\")\n",
    "        # 获取质因数列表\n",
    "        factors = prime_factors(num)\n",
    "        # 将质因数列表转换为字符串并用'*'连接\n",
    "        factors_str = '*'.join(map(str, factors))\n",
    "        # 输出质因数分解结果\n",
    "        print(f\"{num}={factors_str}\")\n",
    "    except ValueError as e:\n",
    "        print(f\"输入错误: {e}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "6.输入一个不多于6位的正整数，要求：1.求它是几位数 2.逆序打印出各位数字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这个数是5位数。\n",
      "逆序打印的各位数字是: 54321\n"
     ]
    }
   ],
   "source": [
    "def main():\n",
    "    try:\n",
    "        # 输入一个不多于6位的正整数\n",
    "        num = int(input(\"请输入一个不多于6位的正整数: \"))\n",
    "        \n",
    "        # 检查输入的数字是否合法（正整数且不超过6位）\n",
    "        if num <= 0 or num > 999999:\n",
    "            raise ValueError(\"输入的数字不合法，请确保它是一个不多于6位的正整数。\")\n",
    "        \n",
    "        # 求它是几位数\n",
    "        num_digits = len(str(num))\n",
    "        print(f\"这个数是{num_digits}位数。\")\n",
    "        \n",
    "        # 逆序打印出各位数字\n",
    "        reversed_num_str = str(num)[::-1]#数字转换为字符串，使用切片操作[::-1]逆序打印各位数字\n",
    "        print(f\"逆序打印的各位数字是: {reversed_num_str}\")\n",
    "        \n",
    "    except ValueError as e:\n",
    "        print(f\"输入错误: {e}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "8.求s=a+aa+aaa+aaaa+aa...a的值，其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加)，几个数相加有键盘控制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s = 370368\n"
     ]
    }
   ],
   "source": [
    "def main():\n",
    "    try:\n",
    "        # 输入数字a\n",
    "        a = int(input(\"请输入一个数字a: \"))\n",
    "        \n",
    "        # 确保a是一个介于0和9之间的单个数字\n",
    "        if a < 0 or a > 9:\n",
    "            raise ValueError(\"数字a必须是一个介于0和9之间的单个数字。\")\n",
    "        \n",
    "        # 输入相加的项数n\n",
    "        n = int(input(\"请输入相加的项数n: \"))\n",
    "        \n",
    "        # 确保n是一个正整数\n",
    "        if n <= 0:\n",
    "            raise ValueError(\"相加的项数n必须是一个正整数。\")\n",
    "        \n",
    "        # 初始化总和s\n",
    "        s = 0\n",
    "        \n",
    "        # 当前项的值，初始为0（用于构建如aa, aaa, aaaa...这样的数）\n",
    "        current_term = 0\n",
    "        \n",
    "        # 循环构建每一项并累加到s中\n",
    "        for i in range(1, n + 1):\n",
    "            # 构建当前项，例如第1项是a, 第2项是aa, 第3项是aaa...\n",
    "            current_term = current_term * 10 + a\n",
    "            # 将当前项累加到s中\n",
    "            s += current_term\n",
    "        \n",
    "        # 输出结果\n",
    "        print(f\"s = {s}\")\n",
    "    \n",
    "    except ValueError as e:\n",
    "        print(f\"输入错误: {e}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10.有一分数序列：2/1，3/2，5/3，8/5，13/8，21/13...求出这个数列的前N项之和，N由键盘输入。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "分数序列的前5项之和是: 1007/120\n"
     ]
    }
   ],
   "source": [
    "from fractions import Fraction\n",
    "\n",
    "def generate_fraction_sequence(n):\n",
    "    # 初始化序列的前两项\n",
    "    fractions = [Fraction(2, 1), Fraction(3, 2)]\n",
    "    \n",
    "    # 生成剩余的项\n",
    "    for i in range(2, n):\n",
    "        next_numerator = fractions[-1].numerator + fractions[-2].numerator\n",
    "        next_denominator = fractions[-1].denominator + fractions[-2].denominator\n",
    "        fractions.append(Fraction(next_numerator, next_denominator))\n",
    "    \n",
    "    return fractions\n",
    "\n",
    "def sum_fraction_sequence(fractions):\n",
    "    # 计算分数序列的和\n",
    "    total_sum = Fraction(0, 1)  # 初始化总和为0（以Fraction形式）\n",
    "    for fraction in fractions:\n",
    "        total_sum += fraction\n",
    "    return total_sum\n",
    "\n",
    "def main():\n",
    "    # 从键盘输入N\n",
    "    N = int(input(\"请输入要计算的项数N: \"))\n",
    "    \n",
    "    # 生成分数序列\n",
    "    fractions = generate_fraction_sequence(N)\n",
    "    \n",
    "    # 计算并输出前N项之和\n",
    "    total_sum = sum_fraction_sequence(fractions)\n",
    "    print(f\"分数序列的前{N}项之和是: {total_sum}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "12.一个整数，它加上100后是一个完全平方数，再加上268又是一个完全平方数，请问该数是多少？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "满足条件的整数是: 4256\n"
     ]
    }
   ],
   "source": [
    "def find_special_number():\n",
    "    for x in range(1, 10000):  # 设定一个合理的范围来搜索\n",
    "        if int(math.sqrt(x + 100))**2 == x + 100 and int(math.sqrt(x + 368))**2 == x + 368:\n",
    "            #计算平方根，检查平方根是否为整数\n",
    "            return x\n",
    "    return None\n",
    "\n",
    "import math\n",
    "\n",
    "result = find_special_number()\n",
    "if result is not None:\n",
    "    print(f\"满足条件的整数是: {result}\")\n",
    "else:\n",
    "    print(\"未找到满足条件的整数。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "14.有一对兔子，从出生后第3个月起每个月都生一对兔子，小兔子长到第三个月后每个月又生一对兔子，假如兔子都不死，问每个月的兔子总数为多少？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第1个月的兔子总数为: 1\n",
      "第2个月的兔子总数为: 1\n",
      "第3个月的兔子总数为: 2\n",
      "第4个月的兔子总数为: 3\n",
      "第5个月的兔子总数为: 5\n",
      "第6个月的兔子总数为: 8\n",
      "第7个月的兔子总数为: 13\n",
      "第8个月的兔子总数为: 21\n",
      "第9个月的兔子总数为: 34\n",
      "第10个月的兔子总数为: 55\n"
     ]
    }
   ],
   "source": [
    "def fibonacci_recursive(n):\n",
    "    # 递归方法计算斐波那契数列（从第3个月起，每个月兔子总数等于前两个月之和）\n",
    "    if n <= 0:\n",
    "        return 0\n",
    "    elif n == 1 or n == 2:\n",
    "        return 1\n",
    "    else:\n",
    "        return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)\n",
    "\n",
    "def fibonacci_iterative(n):\n",
    "    # 迭代方法计算斐波那契数列\n",
    "    if n <= 0:\n",
    "        return 0\n",
    "    elif n == 1 or n == 2:\n",
    "        return 1\n",
    "    \n",
    "    a, b = 1, 1\n",
    "    for _ in range(3, n + 1):\n",
    "        a, b = b, a + b\n",
    "    return b\n",
    "\n",
    "def main():\n",
    "    # 假设我们要计算前m个月的兔子总数\n",
    "    m = int(input(\"请输入要计算的月份数m: \"))\n",
    "    \n",
    "    # 使用迭代方法计算每个月的兔子总数，并打印结果\n",
    "    for i in range(1, m + 1):\n",
    "        print(f\"第{i}个月的兔子总数为: {fibonacci_iterative(i)}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "16.任意输入一个3x3矩阵，求矩阵对角线元素之和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "主对角线元素之和为: 3\n",
      "副对角线元素之和为: 3\n"
     ]
    }
   ],
   "source": [
    "def input_matrix():\n",
    "    # 输入一个3x3矩阵\n",
    "    matrix = []\n",
    "    for i in range(3):\n",
    "        row = list(map(int, input(f\"请输入第{i+1}行的三个整数（用空格分隔）: \").split()))\n",
    "        if len(row) != 3:\n",
    "            raise ValueError(\"每一行必须包含三个整数。\")\n",
    "        matrix.append(row)\n",
    "    return matrix\n",
    "\n",
    "def calculate_diagonal_sums(matrix):\n",
    "    # 计算主对角线和副对角线的和\n",
    "    main_diagonal_sum = sum(matrix[i][i] for i in range(3))\n",
    "    anti_diagonal_sum = sum(matrix[i][2-i] for i in range(3))\n",
    "    #每列和行i从0开始\n",
    "    return main_diagonal_sum, anti_diagonal_sum\n",
    "\n",
    "def main():\n",
    "    # 主程序\n",
    "    try:\n",
    "        matrix = input_matrix()\n",
    "        main_diagonal_sum, anti_diagonal_sum = calculate_diagonal_sums(matrix)\n",
    "        \n",
    "        print(f\"主对角线元素之和为: {main_diagonal_sum}\")\n",
    "        print(f\"副对角线元素之和为: {anti_diagonal_sum}\")\n",
    "    \n",
    "    except ValueError as e:\n",
    "        print(e)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "18.有n个整数，使其前面各数顺序向后移m个位置，最后m个数变成最前面的m个数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "旋转后的列表为: [8, 7, 5, 6, 9]\n"
     ]
    }
   ],
   "source": [
    "def rotate_list(nums, m):\n",
    "    # 确保m不大于列表长度\n",
    "    m = m % len(nums)  # 如果m大于列表长度，取模得到等效的移动步数\n",
    "    \n",
    "    # 使用切片操作来旋转列表\n",
    "    rotated_nums = nums[-m:] + nums[:-m]\n",
    "    #nums[-m:]：这部分代码获取列表nums中从倒数第m个元素开始到列表末尾的所有元素。即获取最后m个元素。\n",
    "    #nums[:-m]：这部分代码获取列表nums中从开始到倒数第m个元素之前（不包括倒数第m个元素）的所有元素。这实际上就是去掉了最后m个元素的剩余部分。\n",
    "\n",
    "    return rotated_nums\n",
    "\n",
    "def main():\n",
    "    # 输入整数n，表示列表的长度\n",
    "    n = int(input(\"请输入整数n，表示列表的长度: \"))\n",
    "    \n",
    "    # 输入n个整数\n",
    "    nums = list(map(int, input(f\"请输入{n}个整数（用空格分隔）: \").split()))\n",
    "    \n",
    "    # 确保输入的整数数量与n一致\n",
    "    if len(nums) != n:\n",
    "        raise ValueError(\"输入的整数数量与n不一致。\")\n",
    "    \n",
    "    # 输入整数m，表示要移动的位置数\n",
    "    m = int(input(\"请输入整数m，表示要移动的位置数: \"))\n",
    "    \n",
    "    # 调用函数旋转列表\n",
    "    rotated_nums = rotate_list(nums, m)\n",
    "    \n",
    "    # 输出旋转后的列表\n",
    "    print(\"旋转后的列表为:\", rotated_nums)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "20.编写一个函数，输入n为偶数时，调用函数求1/2+1/4+...+1/n,当输入n为奇数时，调用函数1/1+1/3+...+1/n(利用指针函数)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "序列的和为: 0.75\n"
     ]
    }
   ],
   "source": [
    "def sum_even_series(n):\n",
    "    \"\"\"计算偶数序列的和：1/2 + 1/4 + ... + 1/n\"\"\"\n",
    "    return sum(1 / i for i in range(2, n + 1, 2))\n",
    "\n",
    "def sum_odd_series(n):\n",
    "    \"\"\"计算奇数序列的和：1/1 + 1/3 + ... + 1/n\"\"\"\n",
    "    return sum(1 / i for i in range(1, n + 1, 2))\n",
    "\n",
    "def calculate_series(n, func):\n",
    "    \"\"\"根据提供的函数来计算序列的和\"\"\"\n",
    "    return func(n)\n",
    "\n",
    "# 主程序\n",
    "def main():\n",
    "    n = int(input(\"请输入一个正整数n: \"))\n",
    "    \n",
    "    if n <= 0:\n",
    "        print(\"请输入一个正整数。\")\n",
    "        return\n",
    "    \n",
    "    # 根据n的奇偶性选择正确的函数\n",
    "    if n % 2 == 0:\n",
    "        result = calculate_series(n, sum_even_series)\n",
    "    else:\n",
    "        result = calculate_series(n, sum_odd_series)\n",
    "    \n",
    "    # 输出结果\n",
    "    print(f\"序列的和为: {result}\")\n",
    "\n",
    "# 运行主程序\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
